#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <pthread.h>
#include <string.h>
#include "shm_reader.h"
#include "mqtt_handler.h"
#include "msg_queue.h"

// 全局变量
static int running = 1;
MQTTClient mqttClient;
mqd_t msg_queue;


// MQTT消息回调
int mqtt_callback(void* context, char* topicName, int topicLen, MQTTClient_message* message) {
    char* payload = (char*)message->payload;
    printf("Received MQTT command: %s\n", payload);
    
    
// 快速查找type字段的值
    int type = -1;
    char* type_ptr = strstr(payload, "\"type\":");
    if (type_ptr != NULL) {
        // 跳过"type": 定位到值的位置
        char* value_ptr = type_ptr + 6;  // "\"type\":" 长度
        
        // 跳过空格和冒号
        while (*value_ptr && (*value_ptr == ' ' || *value_ptr == ':')) 
            value_ptr++;
        
        // 提取数字值
        if (*value_ptr >= '0' && *value_ptr <= '9') {
            type = atoi(value_ptr);
        }
    }

    // 根据类型处理
    switch (type) {
        case 1:  // 控制命令
            send_to_queue(msg_queue, payload);
            break;
        case 2:  // 切换模式
            printf("Switching operation mode\n");
            // 添加模式切换逻辑
            break;
        case 3:  // 刷新命令
            printf("Processing refresh command\n");
            // 添加刷新逻辑
            break;
        default:
            printf("Unknown command type: %d\n", type);
    }
    
    MQTTClient_freeMessage(&message);
    return 1;
}

// 传感器数据读取线程
void* sensor_thread(void* arg) {
    char* shm_ptr = init_shm();
    
    
    while (running) {
        char* sensor_data = read_shm_data(shm_ptr);
        if (sensor_data && strlen(sensor_data) > 0) {
            printf("Sending sensor data: %s\n", sensor_data);
            mqtt_publish(mqttClient, "sensor/data", sensor_data);
        }
        free(sensor_data);
        sleep(2); // 2s读取间隔
    }
    return NULL;
}



void sig_handler(int sig) {
    if (sig == SIGINT) {
        running = 0;
    }
}

int main() {
    // 初始化消息队列（网关只写）
    msg_queue = create_msg_queue();
    
    // 初始化MQTT
    //MQTTClient client;
    mqtt_init(&mqttClient, mqtt_callback);
    mqtt_subscribe(mqttClient, "gateway/commands");
    
    // 创建传感器线程
    pthread_t sensor_tid;
    pthread_create(&sensor_tid, NULL, sensor_thread, NULL);
    
    // 主循环
    while(running) {
        pause(); // 简单等待信号
    }
    
    // 清理
    mqtt_cleanup(mqttClient);
    close_msg_queue(msg_queue);
    return 0;
}